<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TranslatorPro - 专业翻译与变量名生成工具</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --light: #f8f9fa;
            --dark: #212529;
            --success: #4cc9f0;
            --warning: #ff9e00;
            --danger: #e63946;
            --gray: #6c757d;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        header {
            background: var(--primary);
            color: white;
            padding: 30px 40px;
            text-align: center;
            position: relative;
        }
        
        header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        header p {
            font-size: 1.1rem;
            opacity: 0.9;
            max-width: 700px;
            margin: 0 auto;
        }
        
        .logo {
            position: absolute;
            top: 20px;
            left: 30px;
            font-size: 1.8rem;
            background: white;
            color: var(--primary);
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
        
        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            padding: 25px;
            transition: transform 0.3s ease;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .card-title {
            font-size: 1.5rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .card-title i {
            color: var(--primary);
        }
        
        .input-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--dark);
        }
        
        textarea, select, input {
            width: 100%;
            padding: 14px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            background: #fafafa;
            transition: all 0.3s;
        }
        
        textarea {
            min-height: 150px;
            resize: vertical;
        }
        
        textarea:focus, select:focus, input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
            background: white;
        }
        
        .btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 14px 25px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn:hover {
            background: var(--secondary);
            transform: translateY(-2px);
        }
        
        .btn-outline {
            background: transparent;
            border: 2px solid var(--primary);
            color: var(--primary);
        }
        
        .btn-outline:hover {
            background: var(--primary);
            color: white;
        }
        
        .btn-warning {
            background: var(--warning);
        }
        
        .btn-warning:hover {
            background: #ff8c00;
        }
        
        .result-container {
            margin-top: 25px;
            padding: 20px;
            background: #f8f9ff;
            border-radius: 8px;
            border: 1px dashed #d0d7ff;
            min-height: 150px;
        }
        
        .result-item {
            padding: 12px 15px;
            background: white;
            border-radius: 6px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            border-left: 3px solid var(--primary);
        }
        
        .result-text {
            flex: 1;
            word-break: break-all;
            padding-right: 15px;
        }
        
        .copy-btn {
            background: #f0f4ff;
            border: none;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: var(--primary);
            transition: all 0.3s;
        }
        
        .copy-btn:hover {
            background: var(--primary);
            color: white;
        }
        
        .api-selector {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .api-option {
            flex: 1;
            min-width: 200px;
        }
        
        .history-section {
            grid-column: 1 / -1;
            margin-top: 20px;
        }
        
        .history-list {
            max-height: 300px;
            overflow-y: auto;
            margin-top: 20px;
        }
        
        .history-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .history-content {
            flex: 1;
        }
        
        .history-type {
            font-size: 0.8rem;
            padding: 3px 8px;
            border-radius: 20px;
            background: #e0e7ff;
            color: var(--primary);
        }
        
        .clear-history {
            text-align: right;
            margin-top: 15px;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            background: var(--success);
            color: white;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            transform: translateX(120%);
            transition: transform 0.3s ease;
            z-index: 1000;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification.error {
            background: var(--danger);
        }
        
        .api-info {
            background: #f0f7ff;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
            font-size: 0.9rem;
        }
        
        .api-info h4 {
            margin-bottom: 8px;
            color: var(--primary);
        }
        
        footer {
            text-align: center;
            padding: 20px;
            color: var(--gray);
            font-size: 0.9rem;
            border-top: 1px solid #eee;
        }
        
        .toggle-history {
            background: none;
            border: none;
            color: var(--primary);
            cursor: pointer;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 5px;
            margin-top: 10px;
        }
        
        .spinner {
            border: 3px solid rgba(67, 97, 238, 0.2);
            border-top: 3px solid var(--primary);
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .error-message {
            color: var(--danger);
            padding: 15px;
            background: #ffebee;
            border-radius: 8px;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="logo">
                <i class="fas fa-language"></i>
            </div>
            <h1>TranslatorPro</h1>
            <p>专业在线翻译工具 - 支持普通翻译、变量名生成，无需API密钥</p>
        </header>
        
        <div class="main-content">
            <!-- API 选择区域 -->
            <div class="card" style="grid-column: 1 / -1;">
                <div class="card-header">
                    <h2 class="card-title"><i class="fas fa-plug"></i> 选择翻译API</h2>
                </div>
                <div class="api-selector">
                    <div class="api-option">
                        <label for="api-select">当前使用的API：</label>
                        <select id="api-select">
                            <option value="google">Google翻译 (公共接口)</option>
                            <option value="mymemory">MyMemory翻译 (全球最大)</option>
                            <option value="libretranslate">LibreTranslate (开源)</option>
                            <option value="argostranslate">ArgosTranslate (开源替代)</option>
                        </select>
                    </div>
                    <div class="api-option">
                        <label>API状态：<span id="api-status" style="color: var(--success);">✓ 可用</span></label>
                        <div style="display: flex; gap: 10px; margin-top: 8px;">
                            <button class="btn btn-warning" id="test-api">
                                <i class="fas fa-bolt"></i> 测试API
                            </button>
                            <button class="btn btn-outline" id="api-info-btn">
                                <i class="fas fa-info-circle"></i> API信息
                            </button>
                        </div>
                    </div>
                </div>
                <div class="api-info" id="api-info" style="display: none;">
                    <h4>API 使用说明</h4>
                    <p>• <strong>Google翻译</strong>: 使用公共接口，支持大多数语言，但偶尔可能受限</p>
                    <p>• <strong>MyMemory翻译</strong>: 全球最大翻译记忆库，支持170+语言</p>
                    <p>• <strong>LibreTranslate</strong>: 开源翻译服务，支持文本翻译</p>
                    <p>• <strong>ArgosTranslate</strong>: LibreTranslate替代实例，稳定性更好</p>
                    <p>如果某个API不可用，请切换到其他API再试</p>
                </div>
            </div>
            
            <!-- 普通翻译区域 -->
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title"><i class="fas fa-globe"></i> 普通翻译</h2>
                </div>
                
                <div class="input-group">
                    <label for="source-text">输入要翻译的文本（支持多行输入）:</label>
                    <textarea id="source-text" placeholder="输入要翻译的内容..."></textarea>
                </div>
                
                <div class="input-group">
                    <label for="source-lang">源语言:</label>
                    <select id="source-lang">
                        <option value="auto">自动检测</option>
                        <option value="zh">中文</option>
                        <option value="en">英语</option>
                        <option value="es">西班牙语</option>
                        <option value="fr">法语</option>
                        <option value="de">德语</option>
                        <option value="ja">日语</option>
                        <option value="ko">韩语</option>
                        <option value="ru">俄语</option>
                        <option value="ar">阿拉伯语</option>
                    </select>
                </div>
                
                <div class="input-group">
                    <label for="target-lang">目标语言:</label>
                    <select id="target-lang">
                        <option value="en">英语</option>
                        <option value="zh">中文</option>
                        <option value="es">西班牙语</option>
                        <option value="fr">法语</option>
                        <option value="de">德语</option>
                        <option value="ja">日语</option>
                        <option value="ko">韩语</option>
                        <option value="ru">俄语</option>
                        <option value="ar">阿拉伯语</option>
                    </select>
                </div>
                
                <button class="btn" id="translate-btn">
                    <i class="fas fa-exchange-alt"></i> 开始翻译
                </button>
                
                <div class="result-container">
                    <h3>翻译结果:</h3>
                    <div id="translation-result"></div>
                </div>
            </div>
            
            <!-- 变量名翻译区域 -->
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title"><i class="fas fa-code"></i> 变量名生成</h2>
                </div>
                
                <div class="input-group">
                    <label for="var-source">输入变量描述（每行一个变量）:</label>
                    <textarea id="var-source" placeholder="例如: 用户姓名&#10;订单总数&#10;商品价格"></textarea>
                </div>
                
                <div class="input-group">
                    <label for="variable-style">选择变量命名格式:</label>
                    <select id="variable-style">
                        <option value="camel">小驼峰(userName)</option>
                        <option value="pascal">大驼峰(UserName)</option>
                        <option value="snake">蛇形(user_name)</option>
                        <option value="kebab">短横线(user-name)</option>
                        <option value="upper">大写(USER_NAME)</option>
                    </select>
                </div>
                
                <button class="btn" id="generate-btn">
                    <i class="fas fa-magic"></i> 生成变量名
                </button>
                
                <div class="result-container">
                    <h3>生成的变量名:</h3>
                    <div id="variable-result"></div>
                </div>
            </div>
            
            <!-- 历史记录区域 -->
            <div class="card history-section">
                <div class="card-header">
                    <h2 class="card-title"><i class="fas fa-history"></i> 翻译历史</h2>
                    <button class="btn btn-outline" id="clear-history">
                        <i class="fas fa-trash-alt"></i> 清除历史
                    </button>
                </div>
                
                <div class="history-list" id="history-list">
                    <!-- 历史记录将通过JS动态生成 -->
                </div>
                
                <div class="clear-history">
                    <button class="toggle-history" id="toggle-history">
                        <i class="fas fa-chevron-down"></i> 显示/隐藏历史记录
                    </button>
                </div>
            </div>
        </div>
        
        <footer>
            <p>© 2023 TranslatorPro - 专业在线翻译工具 | 支持多个翻译API | 历史记录保存于本地</p>
        </footer>
    </div>
    
    <div class="notification" id="notification">已复制到剪贴板!</div>
    
    <script>
        // 修复后的API端点，无需密钥
        const apiEndpoints = {
            // Google翻译公共接口 (无需密钥)
            google: async (text, sourceLang, targetLang) => {
                const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}`;
                const response = await fetch(url);
                const data = await response.json();
                return data[0].map(item => item[0]).join('');
            },
            
            // MyMemory翻译API (全球最大的翻译记忆库)
            mymemory: async (text, sourceLang, targetLang) => {
                // 处理自动检测语言的情况
                const langpair = sourceLang === 'auto' ? `auto|${targetLang}` : `${sourceLang}|${targetLang}`;
                const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${langpair}`;
                const response = await fetch(url);
                const data = await response.json();
                return data.responseData.translatedText;
            },
            
            // LibreTranslate开源实例 (无需密钥)
            libretranslate: async (text, sourceLang, targetLang) => {
                const response = await fetch('https://libretranslate.de/translate', {
                    method: 'POST',
                    body: JSON.stringify({
                        q: text,
                        source: sourceLang === 'auto' ? '' : sourceLang,
                        target: targetLang,
                        format: "text"
                    }),
                    headers: {
                        "Content-Type": "application/json"
                    }
                });
                const data = await response.json();
                return data.translatedText;
            },
            
            // ArgosTranslate (LibreTranslate的替代实例)
            argostranslate: async (text, sourceLang, targetLang) => {
                const response = await fetch('https://translate.argosopentech.com/translate', {
                    method: 'POST',
                    body: JSON.stringify({
                        q: text,
                        source: sourceLang === 'auto' ? '' : sourceLang,
                        target: targetLang
                    }),
                    headers: {
                        "Content-Type": "application/json"
                    }
                });
                const data = await response.json();
                return data.translatedText;
            }
        };
        
        // 当前选中的API
        let currentApi = 'google';
        let history = JSON.parse(localStorage.getItem('translationHistory')) || [];
        
        // DOM元素
        const apiSelect = document.getElementById('api-select');
        const translateBtn = document.getElementById('translate-btn');
        const generateBtn = document.getElementById('generate-btn');
        const clearHistoryBtn = document.getElementById('clear-history');
        const toggleHistoryBtn = document.getElementById('toggle-history');
        const notification = document.getElementById('notification');
        const historyList = document.getElementById('history-list');
        const apiStatus = document.getElementById('api-status');
        const testApiBtn = document.getElementById('test-api');
        const apiInfoBtn = document.getElementById('api-info-btn');
        const apiInfoSection = document.getElementById('api-info');
        
        // 设置当前API
        apiSelect.value = currentApi;
        apiSelect.addEventListener('change', () => {
            currentApi = apiSelect.value;
        });
        
        // 显示/隐藏API信息
        apiInfoBtn.addEventListener('click', () => {
            apiInfoSection.style.display = apiInfoSection.style.display === 'none' ? 'block' : 'none';
        });
        
        // 测试API可用性
        testApiBtn.addEventListener('click', async () => {
            apiStatus.innerHTML = '<span class="spinner"></span> 测试中...';
            apiStatus.style.color = 'orange';
            
            try {
                // 测试翻译
                const testText = "hello";
                const translatedText = await apiEndpoints[currentApi](testText, 'auto', 'es');
                
                if (translatedText && translatedText.toLowerCase() !== testText.toLowerCase()) {
                    apiStatus.textContent = '✓ 可用';
                    apiStatus.style.color = 'var(--success)';
                    showNotification(`API测试成功: "${testText}" → "${translatedText}"`);
                } else {
                    throw new Error('API返回无效响应');
                }
            } catch (error) {
                console.error('API测试失败:', error);
                apiStatus.textContent = '✗ 不可用';
                apiStatus.style.color = 'var(--danger)';
                showNotification(`API测试失败: ${error.message}`, true);
            }
        });
        
        // 显示通知
        function showNotification(message, isError = false) {
            notification.textContent = message;
            notification.className = 'notification';
            
            if (isError) {
                notification.classList.add('error');
            } else {
                notification.classList.add('show');
            }
            
            setTimeout(() => {
                notification.classList.remove('show', 'error');
            }, 3000);
        }
        
        // 普通翻译功能
        translateBtn.addEventListener('click', async () => {
            const sourceText = document.getElementById('source-text').value;
            const sourceLang = document.getElementById('source-lang').value;
            const targetLang = document.getElementById('target-lang').value;
            const resultContainer = document.getElementById('translation-result');
            
            if (!sourceText.trim()) {
                showNotification('请输入要翻译的内容');
                return;
            }
            
            resultContainer.innerHTML = '<div class="result-item"><div class="result-text">翻译中...</div></div>';
            
            try {
                // 调用翻译API
                const translatedText = await apiEndpoints[currentApi](sourceText, sourceLang, targetLang);
                
                // 显示翻译结果
                resultContainer.innerHTML = `
                    <div class="result-item">
                        <div class="result-text">${translatedText}</div>
                        <button class="copy-btn" data-text="${translatedText}">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                `;
                
                // 添加到历史记录
                addToHistory({
                    type: 'translation',
                    source: sourceText,
                    result: translatedText,
                    sourceLang: sourceLang,
                    targetLang: targetLang,
                    timestamp: new Date().toISOString()
                });
                
            } catch (error) {
                console.error('翻译失败:', error);
                resultContainer.innerHTML = `
                    <div class="error-message">
                        <strong>翻译失败:</strong> ${error.message || '请尝试切换API或稍后再试'}
                    </div>
                `;
                showNotification('翻译失败，请尝试切换API', true);
            }
        });
        
        // 变量名生成功能
        generateBtn.addEventListener('click', async () => {
            const sourceText = document.getElementById('var-source').value;
            const variableStyle = document.getElementById('variable-style').value;
            const resultContainer = document.getElementById('variable-result');
            
            if (!sourceText.trim()) {
                showNotification('请输入变量描述');
                return;
            }
            
            // 分割多行输入
            const lines = sourceText.split('\n').filter(line => line.trim());
            resultContainer.innerHTML = '<div class="result-item"><div class="result-text">生成中...</div></div>';
            
            try {
                let resultsHTML = '';
                
                // 处理每一行
                for (const line of lines) {
                    // 翻译为英文
                    const englishText = await apiEndpoints[currentApi](line, 'auto', 'en');
                    
                    // 格式化变量名
                    const variableName = formatVariableName(englishText, variableStyle);
                    
                    // 添加到结果
                    resultsHTML += `
                        <div class="result-item">
                            <div class="result-text"><strong>${line}:</strong> ${variableName}</div>
                            <button class="copy-btn" data-text="${variableName}">
                                <i class="fas fa-copy"></i>
                            </button>
                        </div>
                    `;
                    
                    // 添加到历史记录
                    addToHistory({
                        type: 'variable',
                        source: line,
                        result: variableName,
                        style: variableStyle,
                        timestamp: new Date().toISOString()
                    });
                }
                
                resultContainer.innerHTML = resultsHTML;
                
            } catch (error) {
                console.error('变量名生成失败:', error);
                resultContainer.innerHTML = `
                    <div class="error-message">
                        <strong>生成失败:</strong> ${error.message || '请尝试切换API或稍后再试'}
                    </div>
                `;
                showNotification('变量名生成失败，请尝试切换API', true);
            }
        });
        
        // 变量名格式化函数
        function formatVariableName(text, style) {
            // 移除特殊字符，只保留字母、数字和空格
            let cleaned = text.replace(/[^a-zA-Z0-9\s]/g, '');
            
            // 转换为小写并用空格分割单词
            let words = cleaned.toLowerCase().split(' ').filter(word => word);
            
            if (words.length === 0) return text;
            
            // 根据选择的样式格式化
            switch(style) {
                case 'camel': // 小驼峰: firstName
                    return words.map((word, i) => 
                        i === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)
                    ).join('');
                    
                case 'pascal': // 大驼峰: FirstName
                    return words.map(word => 
                        word.charAt(0).toUpperCase() + word.slice(1)
                    ).join('');
                    
                case 'snake': // 蛇形: first_name
                    return words.join('_');
                    
                case 'kebab': // 短横线: first-name
                    return words.join('-');
                    
                case 'upper': // 大写: FIRST_NAME
                    return words.join('_').toUpperCase();
                    
                default:
                    return words.join('');
            }
        }
        
        // 添加到历史记录
        function addToHistory(item) {
            history.unshift(item);
            if (history.length > 50) history.pop(); // 限制历史记录数量
            
            localStorage.setItem('translationHistory', JSON.stringify(history));
            renderHistory();
        }
        
        // 渲染历史记录
        function renderHistory() {
            historyList.innerHTML = '';
            
            if (history.length === 0) {
                historyList.innerHTML = '<div class="history-item">暂无历史记录</div>';
                return;
            }
            
            history.forEach((item, index) => {
                const date = new Date(item.timestamp);
                const timeStr = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
                
                const historyItem = document.createElement('div');
                historyItem.className = 'history-item';
                
                // 根据类型显示不同的标签
                let typeLabel = '';
                if (item.type === 'translation') {
                    typeLabel = `<span class="history-type">翻译 ${item.sourceLang}→${item.targetLang}</span>`;
                } else {
                    typeLabel = `<span class="history-type">变量名 (${item.style})</span>`;
                }
                
                historyItem.innerHTML = `
                    <div class="history-content">
                        <div><strong>${item.source}</strong> → ${item.result}</div>
                        <div style="display: flex; gap: 10px; margin-top: 5px;">
                            ${typeLabel}
                            <span style="color: var(--gray); font-size: 0.85rem;">${timeStr}</span>
                        </div>
                    </div>
                    <button class="copy-btn" data-text="${item.result}">
                        <i class="fas fa-copy"></i>
                    </button>
                `;
                
                historyList.appendChild(historyItem);
            });
        }
        
        // 清除历史记录
        clearHistoryBtn.addEventListener('click', () => {
            if (confirm('确定要清除所有历史记录吗?')) {
                history = [];
                localStorage.removeItem('translationHistory');
                renderHistory();
                showNotification('历史记录已清除');
            }
        });
        
        // 复制文本功能（事件委托）
        document.addEventListener('click', (e) => {
            if (e.target.closest('.copy-btn')) {
                const btn = e.target.closest('.copy-btn');
                const text = btn.getAttribute('data-text');
                
                navigator.clipboard.writeText(text)
                    .then(() => showNotification('已复制到剪贴板!'))
                    .catch(err => {
                        console.error('复制失败:', err);
                        showNotification('复制失败', true);
                    });
            }
        });
        
        // 显示/隐藏历史记录
        let historyVisible = true;
        toggleHistoryBtn.addEventListener('click', () => {
            historyVisible = !historyVisible;
            historyList.style.display = historyVisible ? 'block' : 'none';
            toggleHistoryBtn.innerHTML = historyVisible ? 
                '<i class="fas fa-chevron-up"></i> 隐藏历史记录' : 
                '<i class="fas fa-chevron-down"></i> 显示历史记录';
        });
        
        // 初始化历史记录
        renderHistory();
    </script>
</body>
</html>